﻿var Files = {
    model: function (d = {}) {
        this.Title = d.Title || "附件上传";
        this.EnTitle = d.EnTitle || "";
        this.Tips = d.Tips || "";
        this.Name = d.Name || 'lg' + lg.GetSN(6, 10);
        this.Value = d.Value || [];
        this.ExportName = d.ExportName || "";
        this.Width = d.Width || "100%";
        this.Required = d.Required || false;
        this.Api = d.Api || "";
        this.IsRender = d.IsRender != undefined ? d.IsRender : true;
        this.IsShow = d.IsShow || false;
        this.IsExport = d.IsExport || false;
        this.IsWhere = d.IsWhere || false;
        this.WhereKey = d.WhereKey || "精确匹配";
        this.MaxSize = d.MaxSize || 1;
        this.FileTypes = d.FileTypes || ['jpg'];
        this.FileCount = d.FileCount || 1;
    },
    component: {
        name: "lg-form-files",
        data: {
            props: {
                items: {
                    type: Array,
                    default: []
                },
                value: {
                    type: [String, Object],
                    default: ""
                },
                data: {
                    type: Object,
                    default: {}
                },
                requestParam: {
                    type: Object,
                    default: null
                },
                //0填写 1查看
                renderType: {
                    type: Number,
                    default: 0
                }
            },
            data() {
                return {
                    files: [],
                    icons: [
                        { icon: "fa fa-file-excel-o", exts: "xls,xlsx" },
                        { icon: "fa fa-file-word-o", exts: "doc,docx" },
                        { icon: "fa fa-file-archive-o", exts: "rar,zip" },
                        { icon: "fa fa-file-text-o", exts: "txt" },
                        { icon: "fa fa-file-image-o", exts: "jpg,jpeg,png,gif" },
                        { icon: "fa fa-file-audio-o", exts: "mp3" },
                        { icon: "fa fa-file-video-o", exts: "mp4" },
                        { icon: "fa fa-file-pdf-o", exts: "pdf" },
                    ]
                }
            },
            mounted: function () {
                if (this.value && this.value.length > 0) {
                    var arr = lg.obj.copy(this.value);
                    for (let i in arr) {
                        this.files.push({
                            file: null,
                            size: 0,
                            name: arr[i].split("/").pop(),
                            extend: arr[i].split('.').pop(),
                            url: arr[i],
                            data: "",
                            state: "success",
                            isSave: true,
                            progress: "100",
                            errMsg: ""
                        })
                    }

                }
            },
            methods: {
                getIcon: function (ext) {
                    var arr = this.icons.filter(p => p.exts.indexOf(ext) > -1);
                    if (arr.length > 0) {
                        return arr[0].icon
                    } else {
                        return "";
                    }
                },
                onSelect: function () {
                    if (this.renderType == 1) {
                        this.$emit("event", { "type": "file", "name": this.data.Name, "eventName": "load" });
                    } else {
                        this.$refs.fileSelector.click();
                    }

                },
                onSelected: function () {
                    var that = this;
                    var files = this.$refs.fileSelector.files;
                    //校验文件数，未选择文件则不执行任何事件
                    if (files.length == 0) {
                        return false;
                    }
                    //校验选择的文件数量是否超出限制
                    if (files.length + this.files.length > this.data.FileCount) {
                        layer.msg("文件数量超出限制，最大允许文件数为：" + this.data.FileCount + ";如果有失败的文件请删除！", { icon: 2 });
                        return false;
                    }
                    //校验文件尺寸和格式

                    //先将选中的文件添加至待上传的文件列表中
                    for (var i = 0; i < files.length; i++) {
                        var file = files[i];
                        var _file = {
                            file: file,
                            size: (file.size / 1024 / 1024).toFixed(2),
                            name: file.name,
                            extend: file.name.split('.').pop(),
                            url: "",
                            data: "",
                            state: "wait",
                            isSave: false,
                            progress: "1",
                            errMsg: ""
                        }
                        if (_file.size > parseFloat(this.data.MaxSize)) {
                            _file.state = "fail";
                            _file.progress = "100";
                            _file.errMsg = "文件尺寸超限！最大允许上传" + this.data.MaxSize + "M!"
                        }
                        if (this.data.FileTypes.filter(p => p == _file.extend).length == 0) {
                            _file.state = "fail";
                            _file.progress = "100";
                            _file.errMsg = "文件类型不支持！允许的类型：" + JSON.stringify(this.data.FileTypes)
                        }
                        this.files.push(_file)
                    }
                    if (window.FileReader) {
                        for (let i in this.files) {
                            var file = this.files[i];
                            if (file.state == "wait") {
                                this.upFile(file);
                            }

                        }
                    } else {
                        layer.msg("您的浏览器不支持上传插件！", { icon: 2 })
                    }
                    this.$refs.fileSelector.value = '';
                },
                upFile: function (file) {
                    var fd = new FormData();
                    fd.append("file", file.file);
                    fd.append("name", this.data.Name);
                    if (this.requestParam != null) {
                        for (let key in this.requestParam) {
                            fd.append(key, this.requestParam[key]);
                        }
                    }
                    lg.postFile({
                        url: this.data.Api,
                        data: fd,
                        success: res => {
                            if (res.code == 0) {
                                file.state = "success";
                                file.progress = "100";
                                file.url = res.data;
                                this.setValue();
                            } else {
                                file.state = "fail";
                                file.progress = "100";
                                file.errMsg = res.msg;
                            }
                        },
                        fail: res => {
                            file.state = "fail";
                            file.progress = "100";
                            file.errMsg = "接口请求异常！";
                        }
                    })
                },
                remove: function (i) {
                    var that = this;
                    layer.confirm("确定要移除当前文件吗？", function (box) {
                        layer.close(box);
                        that.files.splice(i, 1);
                    })
                },
                setValue: function () {
                    var arr = this.files.filter(p => p.state == 'success');
                    var value = [];
                    if (arr.length > 0) {
                        for (let i in arr) {
                            value.push(arr[i].url)
                        }
                        this.$emit("update:value", value);
                    }
                },
                open: function (file) {
                    window.open(file.url, "_blank");
                }
            },
            template: `
<div :class="['lg-form-item','pane',{'lg-ver-error':data.error}]" :style="{'width':data.Width}">
	<div class="lg-form-block">
		<div class="lg-form-title">
			<div class="lg-form-title-item">
				<i v-if="data.Required">*</i>
				<span class="cn">{{data.Title}}</span>
				<span class="en">{{data.EnTitle}}</span>
			</div>
		</div>
		<div class="lg-upload">
			<input type="file" id="fileUp" class="hide" multiple ref='fileSelector' v-on:change="onSelected" />
			<div class="lg-file-btn" v-on:click="onSelect"><!--上传按钮-->
				<span class="fa fa-cloud-upload btn-file" v-if="renderType==0">上传</span>
				<span class="fa fa-download btn-file" v-if="renderType==1">下载</span>
			</div>
			<!--上传的文件-->
			<div :class="['lg-file-item','lg-file-'+item.state]" v-for="(item,index) in files">
				<div class="lg-file-item-control">
					<div class="lg-file-item-text">
						<span :class="['file-icon',getIcon(item.extend)]"></span>
						<span class="file-name">{{item.name}}</span>
						<span :class="['file-state','fa',{'fa-check':item.state=='success'},{'fa-close':item.state=='fail'},{'fa-spinner fa-pulse':item.state=='process'}]" v-if="renderType==0"></span>
                        <span class="file-del fa fa-eye" title='查看文件' v-on:click='open(item)' v-if="renderType==1" ></span>
					</div>
					<div class="lg-file-item-tool">
						<span class="file-del fa fa-trash-o" title="移除文件" v-on:click='remove(index)'
							v-if="renderType==0"></span>
					</div>
					<progress class="filepro" max="100" :value="item.progress"> {{item.progress}}% </progress>
				</div>
				<div class="lg-form-tip">
					{{item.errMsg}}
				</div>
			</div>
		</div>
	</div>
	<div class="lg-form-block">
		<div class="lg-form-tip">
			<p>{{data.Tips}}</p>
		</div>
		<div class="lg-form-ver" v-if="data.error">{{data.errMsg}}</div>
	</div>
</div>
`
        }
    }
}

Files.model.prototype.verify = function () {
    var res = { state: true, msg: "ok" };
    if (this.Required) {

        if (this.Value.length == 0) {
            res.state = false;
            res.msg = "文件未上传!";
            return res;
        }
    }
    return res
}
Files.model.prototype.getValue = function () {
    if (typeof this.Value == 'object' && this.Value.length == 0) {
        return ""
    }
    return this.Value;
}
Files.model.prototype.setValue = function (data) {
    var val = data[this.Name];
    if (typeof val == "object") {
        this.Value = val;
    } else {
        this.Value = lg.convert.toJson(val, "");
    }
}

export { Files }